package com.yuang.library.base;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jakewharton.rxbinding.view.RxView;
import com.umeng.analytics.MobclickAgent;
import com.yuang.library.R;
import com.yuang.library.action.HandlerAction;
import com.yuang.library.action.WaitDialog;
import com.yuang.library.utils.Constants;
import com.yuang.library.utils.Logg;
import com.yuang.library.utils.TUtil;
import com.yuang.library.utils.TitleBuilder;
import com.yuang.library.utils.ToastUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import rx.functions.Action1;

/**
 * Created by Yuang on 17/12/8.
 * Summary:Fragment基类
 */
public abstract class BaseFragment<T extends BasePresenter,
        E extends BaseModel> extends SupportFragment implements BaseUiInterface , HandlerAction {
    protected String TAG;
    public T mPresenter;
    public E mModel;
    protected Context mContext;
    protected Activity mActivity;
    Unbinder binder;
    private ProgressDialog mProgressDialog;
    private PermissionListener mListener;
    public DecimalFormat decimalFormat;
    /**
     * 加载对话框
     */
    private BaseDialog mDialog;
    /**
     * 对话框数量
     */
    private int mDialogTotal;
    @Override
    public void onAttach(Context context) {
        mActivity = (Activity) context;
        mContext = context;
        super.onAttach(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getLayoutView() != null) {
            return getLayoutView();
        } else {
            return inflater.inflate(getLayoutId(), null);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        TAG = getClass().getSimpleName();
        binder = ButterKnife.bind(this, view);
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        if (this instanceof BaseView) mPresenter.attachVM(this, mModel);
        decimalFormat =   new DecimalFormat("0.00");
        getBundle(getArguments());
        initUI(view, savedInstanceState);
        setListeners();
        initData();
        super.onViewCreated(view, savedInstanceState);
    }


    /**
     * 显示加载对话框
     */
    public void showDialog(Context context,String message) {
        mDialogTotal++;
        postDelayed(() -> {
            if (mDialogTotal > 0 && !getActivity().isFinishing()) {
                //if (mDialog == null) {
                mDialog = new WaitDialog.Builder(context)
                        .setCancelable(true)
                        .setMessage(message)
                        .create();
                //}
                if (!mDialog.isShowing()) {
                    mDialog.show();
                }
            }
        },300);
    }

    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        if (mDialogTotal > 0) {
            mDialogTotal--;
        }

        if (mDialogTotal == 0 && mDialog != null && mDialog.isShowing() && !getActivity().isFinishing()) {
            mDialog.dismiss();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (binder != null) binder.unbind();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachVM();
    }

    @Override
    protected FragmentAnimator onCreateFragmentAnimator() {
        FragmentAnimator fragmentAnimator = _mActivity.getFragmentAnimator();
        fragmentAnimator.setEnter(0);
        fragmentAnimator.setExit(0);
        return fragmentAnimator;
    }

    public abstract int getLayoutId();

    public View getLayoutView() {
        return null;
    }

    /**
     * 得到Activity传进来的值
     */
    public void getBundle(Bundle bundle) {

    }

    /**
     * 初始化控件
     */
    public abstract void initUI(View view, @Nullable Bundle savedInstanceState);

    /**
     * 在监听器之前把数据准备好
     */
    public void initData() {

    }

    /**
     * 设置按钮监听
     */
    protected void setListeners() {
        //empty implementation
    }

    protected void setToolBar(Toolbar toolbar, String title) {
        toolbar.setTitle(title);
        toolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(v -> onBackPressedSupport());
    }

    /**
     * 左侧有返回键的标题栏
     * <p>如果在此基础上还要加其他内容,比如右侧有文字按钮,可以获取该方法返回值继续设置其他内容
     *
     * @param title 标题
     */
    protected TitleBuilder initTitleBar(String title) {
        return new TitleBuilder(mActivity)
                .setTitleText(title)
                .setLeftImage(R.mipmap.ic_back)
                .setLeftOnClickListener(v -> {
                    _mActivity.onBackPressed();
                });
    }

    /**
     * 使用默认的throttle设置来注册点击事件。
     *
     * @param view    要注册的View
     * @param action1 点击后执行的事件
     */
    protected void subscribeClick(View view, Action1<Void> action1) {
        RxView.clicks(view)
                .throttleFirst(Constants.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(action1);
    }

    /**
     * 注册点击事件，不允许throttle。
     *
     * @param view    要注册的View
     * @param action1 点击后执行的事件
     */
    protected void subscribeClickWithoutThrottle(View view, Action1<Void> action1) {
        RxView.clicks(view)
                .subscribe(action1);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(mContext);//统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(mContext);
    }

    public void showToast(String msg) {
        ToastUtils.showToast(mContext, msg, Toast.LENGTH_SHORT);
    }

    public void showLog(String msg) {
        Logg.i(msg);
    }


    @Override
    public void showDataException(String msg) {
        showToast(msg);
    }

    @Override
    public void showNetworkException() {
        showToast("网络异常，请稍后重试");
        dismissLoadingDialog();
    }

    @Override
    public void showUnknownException() {
        showToast("未知错误，请稍后重试");
        dismissLoadingDialog();
    }

    @Override
    public void showLoadingComplete() {
        //Empty implementation
    }

    @SuppressWarnings("unchecked")
    protected final <T extends View> T $(@NonNull View view, @IdRes int id) {
        return (T) (view.findViewById(id));
    }

    @Override
    public Dialog showLoadingDialog(String msg) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        if (TextUtils.isEmpty(msg)) {
            msg = "请稍后";
        }
        mProgressDialog = ProgressDialog.show(getActivity(), null, msg, true, false);
        return mProgressDialog;
    }

    @Override
    public void dismissLoadingDialog() {
        if (mProgressDialog == null || (!mProgressDialog.isShowing())) {
            return;
        }
        mProgressDialog.dismiss();
        mProgressDialog = null;
    }

    /**
     * 授权运行
     *
     * @param permissions 需要权限
     * @param listener    权限监听
     */
    public void requestRunPermission(String[] permissions, PermissionListener listener) {
        mListener = listener;
        List<String> permissionLists = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(permission);
            }
        }

        if (!permissionLists.isEmpty()) {
            ActivityCompat.requestPermissions(getActivity(), permissionLists.toArray(new String[permissionLists.size()]), 10010);
        } else {
            //表示全都授权了
            mListener.onGranted();
        }
    }

    /**
     * 申请授权处理结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 10010:
                try {
                    if (grantResults.length > 0) {
                        //存放没授权的权限
                        List<String> deniedPermissions = new ArrayList<>();
                        for (int i = 0; i < grantResults.length; i++) {
                            int grantResult = grantResults[i];
                            String permission = permissions[i];
                            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                                deniedPermissions.add(permission);
                            }
                        }
                        if (deniedPermissions.isEmpty()) {
                            //说明都授权了
                            mListener.onGranted();
                        } else {
                            mListener.onDenied(deniedPermissions);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}
